from rest_framework import serializers

from courses.models import Teacher, Course, CourseLesson, CourseChapter


class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        fields = ['name', 'title']


class CourseSerializer(serializers.ModelSerializer):
    # 嵌套 序列化讲师的信息
    teacher = TeacherSerializer(read_only=True)

    # 自定义字段:付费类型
    course_type_text = serializers.SerializerMethodField()

    class Meta:
        model = Course
        fields = ['id', 'course_img', 'name', 'brief', 'teacher', 'students', 'lessons', 'course_type',
                  'course_type_text',
                  'original_price', 'price']

    def get_course_type_text(self, obj):
        return obj.get_course_type_display()


class TeacherDetailSerializer(serializers.ModelSerializer):
    """
    讲师详情
    """

    class Meta:
        model = Teacher
        fields = '__all__'


class LessonDeatilSerializer(serializers.ModelSerializer):
    """
    课时详情
    """

    class Meta:
        model = CourseLesson
        fields = '__all__'


class ChapterSerializer(serializers.ModelSerializer):
    # 通过related_name="lessons" 反向获取课时信息
    lessons = LessonDeatilSerializer(many=True, read_only=True)
    """
    章节
    """

    class Meta:
        model = CourseChapter
        fields = '__all__'


class CourseDetailSerializer(serializers.ModelSerializer):
    chapters = ChapterSerializer(many=True, read_only=True)

    teacher = TeacherDetailSerializer(read_only=True)

    class Meta:
        model = Course
        fields = '__all__'


class CourseLessonSerializer(serializers.ModelSerializer):
    """
    课时
    """

    lesson_type_text = serializers.CharField(source='get_lesson_type_display', read_only=True)

    class Meta:
        model = CourseLesson
        fields = ['id', 'title', 'orders', 'lesson_type', 'lesson_type_text', 'link', 'duration', 'pub_date',
                  'is_free_trail']


class CourseChapterSerializer(serializers.ModelSerializer):
    """
    课程章节
    """
    lessons = CourseLessonSerializer(many=True, read_only=True)

    class Meta:
        model = CourseChapter
        fields = ['id', 'title', 'number', 'summary', 'pub_date', 'lessons']
